"""
AI算法相关的API端点
"""
import asyncio
import logging
from datetime import datetime, timedelta
from typing import List, Dict, Optional, Any
from fastapi import APIRouter, HTTPException, Depends, BackgroundTasks, UploadFile, File
from fastapi.responses import JSONResponse
import cv2
import numpy as np
import base64

from schemas.ai_algorithm import (
    DetectionRequest, DetectionResponse, AIModelConfig, 
    BehaviorAnalysisResult, AlertRule, AlertEvent, AlertLevel,
    BatchDetectionRequest, BatchDetectionResponse, ModelPerformanceMetrics
)
from schemas.person_detection import (
    PersonDetectionResult, DetectionConfig, DetectionTask, ModelInfo
)
from services.person_detection_service import person_detection_service
from services.behavior_analysis_service import behavior_analysis_service
from services.alerts.intelligent_alert_service import intelligent_alert_service
from services.pose_detection_service import pose_detection_service
from services.conflict_detection_service import conflict_detection_service
from services.trajectory_analysis_service import trajectory_analysis_service
from core.auth import get_current_user
from core.config import get_settings

logger = logging.getLogger(__name__)
settings = get_settings()

router = APIRouter()


# 人员检测相关端点
@router.post("/detection/person", response_model=PersonDetectionResult)
async def detect_persons(
    camera_id: str,
    file: UploadFile = File(...),
    config: Optional[DetectionConfig] = None,
    current_user: dict = Depends(get_current_user)
):
    """人员检测"""
    try:
        # 读取上传的图像
        image_data = await file.read()
        nparr = np.frombuffer(image_data, np.uint8)
        image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        if image is None:
            raise HTTPException(status_code=400, detail="Invalid image format")
        
        # 执行检测
        result = await person_detection_service.detect_persons(
            image=image,
            camera_id=camera_id,
            config=config
        )
        
        # 处理检测结果用于行为分析
        await behavior_analysis_service.update_tracks(result)
        
        # 处理检测结果用于告警
        await intelligent_alert_service.process_detection_result(result)
        
        return result
        
    except Exception as e:
        logger.error(f"Person detection failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/detection/batch", response_model=BatchDetectionResponse)
async def batch_detect_persons(
    request: BatchDetectionRequest,
    background_tasks: BackgroundTasks,
    current_user: dict = Depends(get_current_user)
):
    """批量人员检测"""
    try:
        # 这里应该实现批量检测逻辑
        # 为了简化，返回模拟结果
        
        results = []
        for i, detection_request in enumerate(request.requests):
            # 模拟检测结果
            result = PersonDetectionResult(
                detection_id=f"batch_{request.batch_id}_{i}",
                camera_id=detection_request.camera_id,
                timestamp=datetime.now(),
                persons=[],
                total_count=0,
                confidence_threshold=0.5,
                processing_time=0.1
            )
            results.append(result)
        
        response = BatchDetectionResponse(
            batch_id=request.batch_id,
            total_requests=len(request.requests),
            completed_requests=len(results),
            failed_requests=0,
            results=results,
            total_processing_time=sum(r.processing_time for r in results),
            timestamp=datetime.now()
        )
        
        return response
        
    except Exception as e:
        logger.error(f"Batch detection failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/detection/tasks", response_model=List[DetectionTask])
async def get_detection_tasks(
    camera_id: Optional[str] = None,
    current_user: dict = Depends(get_current_user)
):
    """获取检测任务列表"""
    try:
        tasks = await person_detection_service.get_detection_tasks(camera_id)
        return tasks
    except Exception as e:
        logger.error(f"Failed to get detection tasks: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/detection/tasks", response_model=DetectionTask)
async def create_detection_task(
    camera_id: str,
    task_type: str = "person_detection",
    config: Optional[DetectionConfig] = None,
    current_user: dict = Depends(get_current_user)
):
    """创建检测任务"""
    try:
        task = await person_detection_service.create_detection_task(
            camera_id=camera_id,
            task_type=task_type,
            config=config
        )
        return task
    except Exception as e:
        logger.error(f"Failed to create detection task: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/detection/tasks/{task_id}/start")
async def start_detection_task(
    task_id: str,
    current_user: dict = Depends(get_current_user)
):
    """启动检测任务"""
    try:
        success = await person_detection_service.start_detection_task(task_id)
        if not success:
            raise HTTPException(status_code=404, detail="Task not found")
        
        return {"message": "Task started successfully", "task_id": task_id}
    except Exception as e:
        logger.error(f"Failed to start detection task: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/detection/tasks/{task_id}")
async def cancel_detection_task(
    task_id: str,
    current_user: dict = Depends(get_current_user)
):
    """取消检测任务"""
    try:
        success = await person_detection_service.cancel_detection_task(task_id)
        if not success:
            raise HTTPException(status_code=404, detail="Task not found")
        
        return {"message": "Task cancelled successfully", "task_id": task_id}
    except Exception as e:
        logger.error(f"Failed to cancel detection task: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 模型管理相关端点
@router.get("/models", response_model=List[ModelInfo])
async def get_available_models(
    current_user: dict = Depends(get_current_user)
):
    """获取可用模型列表"""
    try:
        models = person_detection_service.get_available_models()
        return models
    except Exception as e:
        logger.error(f"Failed to get available models: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/models/{model_id}", response_model=ModelInfo)
async def get_model_info(
    model_id: str,
    current_user: dict = Depends(get_current_user)
):
    """获取模型信息"""
    try:
        model_info = person_detection_service.get_model_info(model_id)
        if not model_info:
            raise HTTPException(status_code=404, detail="Model not found")
        
        return model_info
    except Exception as e:
        logger.error(f"Failed to get model info: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/models/{model_id}/performance", response_model=List[PerformanceMetrics])
async def get_model_performance(
    model_id: str,
    limit: int = 100,
    current_user: dict = Depends(get_current_user)
):
    """获取模型性能指标"""
    try:
        metrics = await person_detection_service.get_performance_metrics(
            model_id=model_id,
            limit=limit
        )
        return metrics
    except Exception as e:
        logger.error(f"Failed to get model performance: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/models/{model_id}/benchmark")
async def benchmark_model(
    model_id: str,
    test_images: List[UploadFile] = File(...),
    current_user: dict = Depends(get_current_user)
):
    """模型基准测试"""
    try:
        # 处理测试图像
        images = []
        for file in test_images:
            image_data = await file.read()
            nparr = np.frombuffer(image_data, np.uint8)
            image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
            if image is not None:
                images.append(image)
        
        if not images:
            raise HTTPException(status_code=400, detail="No valid images provided")
        
        # 执行基准测试
        results = await person_detection_service.benchmark_model(model_id, images)
        
        return results
        
    except Exception as e:
        logger.error(f"Model benchmark failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 行为分析相关端点
@router.get("/behavior/analysis", response_model=List[BehaviorAnalysisResult])
async def get_behavior_analysis(
    camera_id: Optional[str] = None,
    behavior_types: Optional[List[str]] = None,
    start_time: Optional[datetime] = None,
    end_time: Optional[datetime] = None,
    limit: int = 100,
    current_user: dict = Depends(get_current_user)
):
    """获取行为分析结果"""
    try:
        # 转换行为类型
        behavior_type_enums = None
        if behavior_types:
            from schemas.ai_algorithm import BehaviorType
            behavior_type_enums = [BehaviorType(bt) for bt in behavior_types]
        
        results = await behavior_analysis_service.get_analysis_results(
            camera_id=camera_id,
            behavior_types=behavior_type_enums,
            start_time=start_time,
            end_time=end_time,
            limit=limit
        )
        
        return results
        
    except Exception as e:
        logger.error(f"Failed to get behavior analysis: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/behavior/tracks")
async def get_active_tracks(
    camera_id: Optional[str] = None,
    current_user: dict = Depends(get_current_user)
):
    """获取活跃轨迹"""
    try:
        tracks = await behavior_analysis_service.get_active_tracks(camera_id)
        return tracks
    except Exception as e:
        logger.error(f"Failed to get active tracks: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/behavior/statistics")
async def get_behavior_statistics(
    hours: int = 1,
    current_user: dict = Depends(get_current_user)
):
    """获取行为统计"""
    try:
        time_range = timedelta(hours=hours)
        stats = await behavior_analysis_service.get_behavior_statistics(time_range)
        return stats
    except Exception as e:
        logger.error(f"Failed to get behavior statistics: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/behavior/analysis/start")
async def start_behavior_analysis(
    current_user: dict = Depends(get_current_user)
):
    """启动行为分析"""
    try:
        await behavior_analysis_service.start_analysis()
        return {"message": "Behavior analysis started"}
    except Exception as e:
        logger.error(f"Failed to start behavior analysis: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/behavior/analysis/stop")
async def stop_behavior_analysis(
    current_user: dict = Depends(get_current_user)
):
    """停止行为分析"""
    try:
        await behavior_analysis_service.stop_analysis()
        return {"message": "Behavior analysis stopped"}
    except Exception as e:
        logger.error(f"Failed to stop behavior analysis: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/behavior/crowd-density")
async def analyze_crowd_density(
    camera_id: str,
    file: UploadFile = File(...),
    current_user: dict = Depends(get_current_user)
):
    """分析人群密度"""
    try:
        # 读取图像
        image_data = await file.read()
        nparr = np.frombuffer(image_data, np.uint8)
        image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        if image is None:
            raise HTTPException(status_code=400, detail="Invalid image format")
        
        # 先进行人员检测
        detection_result = await person_detection_service.detect_persons(
            image=image,
            camera_id=camera_id
        )
        
        # 分析人群密度
        image_size = (image.shape[1], image.shape[0])  # (width, height)
        density_result = await behavior_analysis_service.analyze_crowd_density(
            detection_result, image_size
        )
        
        return density_result
        
    except Exception as e:
        logger.error(f"Crowd density analysis failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 告警系统相关端点
@router.get("/alerts/rules")
async def get_alert_rules(
    current_user: dict = Depends(get_current_user)
):
    """获取告警规则"""
    try:
        rules = intelligent_alert_service.get_alert_rules()
        return rules
    except Exception as e:
        logger.error(f"Failed to get alert rules: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/alerts/rules")
async def create_alert_rule(
    rule_config: Dict[str, Any],
    current_user: dict = Depends(get_current_user)
):
    """创建告警规则"""
    try:
        rule_id = intelligent_alert_service.add_alert_rule(rule_config)
        return {"message": "Alert rule created", "rule_id": rule_id}
    except Exception as e:
        logger.error(f"Failed to create alert rule: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/alerts/rules/{rule_id}")
async def update_alert_rule(
    rule_id: str,
    updates: Dict[str, Any],
    current_user: dict = Depends(get_current_user)
):
    """更新告警规则"""
    try:
        success = intelligent_alert_service.update_alert_rule(rule_id, updates)
        if not success:
            raise HTTPException(status_code=404, detail="Rule not found")
        
        return {"message": "Alert rule updated", "rule_id": rule_id}
    except Exception as e:
        logger.error(f"Failed to update alert rule: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/alerts/rules/{rule_id}")
async def delete_alert_rule(
    rule_id: str,
    current_user: dict = Depends(get_current_user)
):
    """删除告警规则"""
    try:
        success = intelligent_alert_service.remove_alert_rule(rule_id)
        if not success:
            raise HTTPException(status_code=404, detail="Rule not found")
        
        return {"message": "Alert rule deleted", "rule_id": rule_id}
    except Exception as e:
        logger.error(f"Failed to delete alert rule: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/alerts/events", response_model=List[AlertEvent])
async def get_alert_events(
    camera_id: Optional[str] = None,
    alert_level: Optional[str] = None,
    start_time: Optional[datetime] = None,
    end_time: Optional[datetime] = None,
    limit: int = 100,
    current_user: dict = Depends(get_current_user)
):
    """获取告警事件"""
    try:
        # 转换告警级别
        alert_level_enum = None
        if alert_level:
            alert_level_enum = AlertLevel(alert_level)
        
        events = intelligent_alert_service.get_alert_events(
            camera_id=camera_id,
            alert_level=alert_level_enum,
            start_time=start_time,
            end_time=end_time,
            limit=limit
        )
        
        return events
        
    except Exception as e:
        logger.error(f"Failed to get alert events: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/alerts/events/{alert_id}/acknowledge")
async def acknowledge_alert(
    alert_id: str,
    current_user: dict = Depends(get_current_user)
):
    """确认告警"""
    try:
        user_id = current_user.get("user_id", "unknown")
        success = intelligent_alert_service.acknowledge_alert(alert_id, user_id)
        
        if not success:
            raise HTTPException(status_code=404, detail="Alert not found")
        
        return {"message": "Alert acknowledged", "alert_id": alert_id}
    except Exception as e:
        logger.error(f"Failed to acknowledge alert: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/alerts/events/{alert_id}/resolve")
async def resolve_alert(
    alert_id: str,
    current_user: dict = Depends(get_current_user)
):
    """解决告警"""
    try:
        user_id = current_user.get("user_id", "unknown")
        success = intelligent_alert_service.resolve_alert(alert_id, user_id)
        
        if not success:
            raise HTTPException(status_code=404, detail="Alert not found")
        
        return {"message": "Alert resolved", "alert_id": alert_id}
    except Exception as e:
        logger.error(f"Failed to resolve alert: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/alerts/statistics")
async def get_alert_statistics(
    hours: int = 24,
    current_user: dict = Depends(get_current_user)
):
    """获取告警统计"""
    try:
        time_range = timedelta(hours=hours)
        stats = intelligent_alert_service.get_alert_statistics(time_range)
        return stats
    except Exception as e:
        logger.error(f"Failed to get alert statistics: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/alerts/service/start")
async def start_alert_service(
    current_user: dict = Depends(get_current_user)
):
    """启动告警服务"""
    try:
        await intelligent_alert_service.start_service()
        return {"message": "Alert service started"}
    except Exception as e:
        logger.error(f"Failed to start alert service: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/alerts/service/stop")
async def stop_alert_service(
    current_user: dict = Depends(get_current_user)
):
    """停止告警服务"""
    try:
        await intelligent_alert_service.stop_service()
        return {"message": "Alert service stopped"}
    except Exception as e:
        logger.error(f"Failed to stop alert service: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/alerts/filter-settings")
async def update_filter_settings(
    settings: Dict[str, Any],
    current_user: dict = Depends(get_current_user)
):
    """更新过滤器设置"""
    try:
        intelligent_alert_service.update_filter_settings(settings)
        return {"message": "Filter settings updated"}
    except Exception as e:
        logger.error(f"Failed to update filter settings: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 配置相关端点
@router.get("/config/detection", response_model=DetectionConfig)
async def get_detection_config(
    current_user: dict = Depends(get_current_user)
):
    """获取检测配置"""
    try:
        config = person_detection_service.get_detection_config()
        return config
    except Exception as e:
        logger.error(f"Failed to get detection config: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.put("/config/detection")
async def update_detection_config(
    config: DetectionConfig,
    current_user: dict = Depends(get_current_user)
):
    """更新检测配置"""
    try:
        person_detection_service.update_detection_config(config)
        return {"message": "Detection config updated"}
    except Exception as e:
        logger.error(f"Failed to update detection config: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 姿态检测和行为识别端点
@router.post("/pose/analyze")
async def analyze_poses(
    camera_id: str,
    file: UploadFile = File(...),
    current_user: dict = Depends(get_current_user)
):
    """姿态检测和行为识别"""
    try:
        # 读取上传的图像
        image_data = await file.read()
        nparr = np.frombuffer(image_data, np.uint8)
        image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        if image is None:
            raise HTTPException(status_code=400, detail="Invalid image format")
        
        # 执行姿态分析
        result = await pose_detection_service.analyze_poses(image, camera_id)
        
        return result
        
    except Exception as e:
        logger.error(f"Pose analysis failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/pose/results")
async def get_pose_analysis_results(
    camera_id: Optional[str] = None,
    start_time: Optional[datetime] = None,
    end_time: Optional[datetime] = None,
    limit: int = 100,
    current_user: dict = Depends(get_current_user)
):
    """获取姿态分析结果"""
    try:
        results = await pose_detection_service.get_analysis_results(
            camera_id=camera_id,
            start_time=start_time,
            end_time=end_time,
            limit=limit
        )
        return results
    except Exception as e:
        logger.error(f"Failed to get pose analysis results: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/pose/alerts")
async def get_behavior_alerts(
    camera_id: Optional[str] = None,
    severity: Optional[str] = None,
    resolved: Optional[bool] = None,
    limit: int = 100,
    current_user: dict = Depends(get_current_user)
):
    """获取行为告警"""
    try:
        from schemas.pose_detection import BehaviorSeverity
        severity_enum = BehaviorSeverity(severity) if severity else None
        
        alerts = await pose_detection_service.get_behavior_alerts(
            camera_id=camera_id,
            severity=severity_enum,
            resolved=resolved,
            limit=limit
        )
        return alerts
    except Exception as e:
        logger.error(f"Failed to get behavior alerts: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 冲突检测端点
@router.post("/conflict/analyze")
async def analyze_conflicts(
    camera_id: str,
    file: UploadFile = File(...),
    current_user: dict = Depends(get_current_user)
):
    """冲突行为分析"""
    try:
        # 读取图像
        image_data = await file.read()
        nparr = np.frombuffer(image_data, np.uint8)
        image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        if image is None:
            raise HTTPException(status_code=400, detail="Invalid image format")
        
        # 先进行姿态检测
        pose_result = await pose_detection_service.analyze_poses(image, camera_id)
        
        # 分析冲突行为
        conflict_result = await conflict_detection_service.analyze_poses(pose_result.poses, camera_id)
        
        return {
            "pose_analysis": pose_result,
            "conflict_analysis": conflict_result
        }
        
    except Exception as e:
        logger.error(f"Conflict analysis failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/conflict/events")
async def get_conflict_events(
    camera_id: Optional[str] = None,
    conflict_type: Optional[str] = None,
    severity: Optional[str] = None,
    start_time: Optional[datetime] = None,
    end_time: Optional[datetime] = None,
    limit: int = 100,
    current_user: dict = Depends(get_current_user)
):
    """获取冲突事件"""
    try:
        from services.conflict_detection_service import ConflictType, ConflictSeverity
        
        conflict_type_enum = ConflictType(conflict_type) if conflict_type else None
        severity_enum = ConflictSeverity(severity) if severity else None
        
        events = await conflict_detection_service.get_conflict_events(
            camera_id=camera_id,
            conflict_type=conflict_type_enum,
            severity=severity_enum,
            start_time=start_time,
            end_time=end_time,
            limit=limit
        )
        return events
    except Exception as e:
        logger.error(f"Failed to get conflict events: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/conflict/bullying")
async def get_bullying_events(
    aggressor_id: Optional[str] = None,
    victim_id: Optional[str] = None,
    pattern_id: Optional[str] = None,
    limit: int = 100,
    current_user: dict = Depends(get_current_user)
):
    """获取霸凌事件"""
    try:
        events = await conflict_detection_service.get_bullying_events(
            aggressor_id=aggressor_id,
            victim_id=victim_id,
            pattern_id=pattern_id,
            limit=limit
        )
        return events
    except Exception as e:
        logger.error(f"Failed to get bullying events: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/conflict/resolve/{event_id}")
async def resolve_conflict(
    event_id: str,
    current_user: dict = Depends(get_current_user)
):
    """解决冲突"""
    try:
        success = await conflict_detection_service.resolve_conflict(event_id)
        if not success:
            raise HTTPException(status_code=404, detail="Conflict event not found")
        
        return {"message": "Conflict resolved", "event_id": event_id}
    except Exception as e:
        logger.error(f"Failed to resolve conflict: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 轨迹分析端点
@router.get("/trajectory/trajectories")
async def get_trajectories(
    person_id: Optional[str] = None,
    trajectory_type: Optional[str] = None,
    is_active: Optional[bool] = None,
    start_time: Optional[datetime] = None,
    end_time: Optional[datetime] = None,
    limit: int = 100,
    current_user: dict = Depends(get_current_user)
):
    """获取轨迹"""
    try:
        from services.trajectory_analysis_service import TrajectoryType
        
        trajectory_type_enum = TrajectoryType(trajectory_type) if trajectory_type else None
        
        trajectories = await trajectory_analysis_service.get_trajectories(
            person_id=person_id,
            trajectory_type=trajectory_type_enum,
            is_active=is_active,
            start_time=start_time,
            end_time=end_time,
            limit=limit
        )
        return trajectories
    except Exception as e:
        logger.error(f"Failed to get trajectories: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/trajectory/behavior-analyses")
async def get_behavior_analyses(
    person_id: Optional[str] = None,
    limit: int = 100,
    current_user: dict = Depends(get_current_user)
):
    """获取行为分析"""
    try:
        analyses = await trajectory_analysis_service.get_behavior_analyses(
            person_id=person_id,
            limit=limit
        )
        return analyses
    except Exception as e:
        logger.error(f"Failed to get behavior analyses: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/trajectory/identities")
async def get_identities(
    identity_status: Optional[str] = None,
    min_risk_score: Optional[float] = None,
    current_user: dict = Depends(get_current_user)
):
    """获取身份信息"""
    try:
        from services.trajectory_analysis_service import IdentityStatus
        
        identity_status_enum = IdentityStatus(identity_status) if identity_status else None
        
        identities = trajectory_analysis_service.get_identities(
            identity_status=identity_status_enum,
            min_risk_score=min_risk_score
        )
        return identities
    except Exception as e:
        logger.error(f"Failed to get identities: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/trajectory/zones")
async def get_spatial_zones(
    current_user: dict = Depends(get_current_user)
):
    """获取空间区域"""
    try:
        zones = trajectory_analysis_service.get_spatial_zones()
        return zones
    except Exception as e:
        logger.error(f"Failed to get spatial zones: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 服务管理端点
@router.post("/services/pose/start")
async def start_pose_service(
    current_user: dict = Depends(get_current_user)
):
    """启动姿态检测服务"""
    try:
        await pose_detection_service.start_service()
        return {"message": "Pose detection service started"}
    except Exception as e:
        logger.error(f"Failed to start pose service: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/services/pose/stop")
async def stop_pose_service(
    current_user: dict = Depends(get_current_user)
):
    """停止姿态检测服务"""
    try:
        await pose_detection_service.stop_service()
        return {"message": "Pose detection service stopped"}
    except Exception as e:
        logger.error(f"Failed to stop pose service: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/services/conflict/start")
async def start_conflict_service(
    current_user: dict = Depends(get_current_user)
):
    """启动冲突检测服务"""
    try:
        await conflict_detection_service.start_service()
        return {"message": "Conflict detection service started"}
    except Exception as e:
        logger.error(f"Failed to start conflict service: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/services/conflict/stop")
async def stop_conflict_service(
    current_user: dict = Depends(get_current_user)
):
    """停止冲突检测服务"""
    try:
        await conflict_detection_service.stop_service()
        return {"message": "Conflict detection service stopped"}
    except Exception as e:
        logger.error(f"Failed to stop conflict service: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/services/trajectory/start")
async def start_trajectory_service(
    current_user: dict = Depends(get_current_user)
):
    """启动轨迹分析服务"""
    try:
        await trajectory_analysis_service.start_service()
        return {"message": "Trajectory analysis service started"}
    except Exception as e:
        logger.error(f"Failed to start trajectory service: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/services/trajectory/stop")
async def stop_trajectory_service(
    current_user: dict = Depends(get_current_user)
):
    """停止轨迹分析服务"""
    try:
        await trajectory_analysis_service.stop_service()
        return {"message": "Trajectory analysis service stopped"}
    except Exception as e:
        logger.error(f"Failed to stop trajectory service: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 统计信息端点
@router.get("/statistics/conflict")
async def get_conflict_statistics(
    current_user: dict = Depends(get_current_user)
):
    """获取冲突统计"""
    try:
        stats = conflict_detection_service.get_statistics()
        return stats
    except Exception as e:
        logger.error(f"Failed to get conflict statistics: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/statistics/trajectory")
async def get_trajectory_statistics(
    current_user: dict = Depends(get_current_user)
):
    """获取轨迹统计"""
    try:
        stats = trajectory_analysis_service.get_statistics()
        return stats
    except Exception as e:
        logger.error(f"Failed to get trajectory statistics: {e}")
        raise HTTPException(status_code=500, detail=str(e))


# 健康检查端点
@router.get("/health")
async def health_check():
    """健康检查"""
    try:
        # 检查各个服务的状态
        status = {
            "person_detection": "healthy",
            "behavior_analysis": "healthy", 
            "intelligent_alert": "healthy",
            "pose_detection": "healthy",
            "conflict_detection": "healthy",
            "trajectory_analysis": "healthy",
            "timestamp": datetime.now().isoformat()
        }
        
        # 可以添加更详细的健康检查逻辑
        
        return status
        
    except Exception as e:
        logger.error(f"Health check failed: {e}")
        raise HTTPException(status_code=500, detail=str(e))